


from common.config import *
import time
import redis, json
pool = redis.ConnectionPool(**rConfig)
r = redis.Redis(connection_pool=pool)


class Helper(object):

    def __init__(self):

        pass

        # 生成加密标签SDK

    @staticmethod
    def genSign(args):
        import hashlib

        # 升序排列
        params = dict(sorted(args.items()))

        # 定义空字符串循环拼接
        s = ''
        for k, v in params.items():
            s += k + v

        # 添加client_key
        msg = secret_key['client_secret'] + s + secret_key['client_secret']

        # MD5加密
        md = hashlib.md5()

        md.update(msg.encode(encoding='utf-8'))

        sign = md.hexdigest().upper()

        return sign

    # 存储到redis
    @staticmethod
    def saveReids(data):

        print(data)

        if data['type'] in [200,201,202]:

            r.lpush('api_tasks', json.dumps(data,ensure_ascii=False))

            print('%s存储到Redis成功...'%data['msg'])

        elif data['type'] in [204,205,207]:

            r.lpush('crawler_tasks', json.dumps(data, ensure_ascii=False))

            print('%s存储到Redis成功...' % data['msg'])
        # 备注任务
        elif data['type'] == 203:

            r.lpush('notes_tasks', json.dumps(data, ensure_ascii=False))

            print('%s存储到Redis成功...' % data['msg'])


        elif data['type'] == 206:

            r.lpush('comments_tasks', json.dumps(data, ensure_ascii=False))

            print('%s存储到Redis成功...' % data['msg'])

        else:

            pass

    # 获取redis队列长度
    @staticmethod
    def lenRedis():

        length = r.llen('tasks')

        return length


    # redis领取任务增量任务
    @staticmethod
    def redisCase( types ):

        n = r.lpop(types)

        if n:

            return n

        return None

        # return json.loads( n.decode('ascii') )


    # base64转换
    @staticmethod
    def changeBase64( args ):

        import base64

        content = base64.b64encode( args.encode('ascii'))

        return content



    #获取pc机信息
    @staticmethod
    def privateInfo( type = None):

        import socket,requests,json,uuid

        # 主机名称
        hostname = socket.gethostname()
        #ip地址
        ip = socket.gethostbyname(hostname)

        mac = uuid.UUID(int=uuid.getnode()).hex[-12:]

        mac = ( "-".join([mac[e:e+2] for e in range(0,11,2)]).upper())

        private = {

            'hostname':hostname,
            'ip':ip,
            'mac':mac

        }

        content = Helper.changeBase64( json.dumps( private ))

        res = {

            'type':type,
            'content':content.decode('ascii')
        }

        res = Helper.changeBase64( json.dumps( res )).decode('ascii')


        return res

    #时间戳转日期
    @staticmethod
    def StampToDate( ts  ):

        utc = time.localtime(ts )

        date = time.strftime("%Y-%m-%d",utc)

        return date

    # 生成九十天之内的时间戳（评价）
    @staticmethod
    def genTimeInterval():
        import time

        data = {}

        end_time = int(time.time())

        start_time = int(end_time - (90 * 24 * 3600))

        data["start_time"] = start_time
        data["end_time"] = end_time

        return data

    # 测试评价请求是否封号
    @staticmethod
    def testCommentTask(arguments=None):

        import requests, json

        header['cookie'] = arguments['cookie']

        data = {"pageSize": 10, "pageNo": 1, "status": 0, "startTime": Helper.genTimeInterval()['start_time'],
                "endTime": Helper.genTimeInterval()['end_time']}

        resp = lambda: requests.post(domain_url['comments_url'], headers=header, data=json.dumps(data))

        r = resp()

        # print( r.text )

        # print( r.json())
        # 判断cookie是否过期
        if r.status_code == 200 and "会话已过期" in json.dumps(r.json(), ensure_ascii=False):

            error = dict(errorCode=r.json()['error_code'], errorMsg=r.json()['error_msg'])

            print(error)
            return  error
        # IP被封号
        elif r.status_code == 200 and not r.json()['result']:

            error = dict(errorCode=r.json()['errorCode'], errorMsg='账号被封禁')

            print(error)

            return False

        # 正常情况
        else:

            return {'errorCode':0,'errorMsg':'操作正常'}


if __name__ == '__main__':


    # h = Helper()
    #
    # task = {
    #     "type": 206,
    #     "content": {
    #         "task_page_id": 12,
    #         "task_id": 1,
    #         "owner_id": 186716817,
    #         "start_time": 1561132800,
    #         "end_time": 1561823999,
    #         "page": 3,
    #         "cookie": "_nano_fp=Xpdjl0UyXpEqn5Tjn9_hcqX3_GdIDNGobRfgDlMO;_nano_fp=Xpdjl0UyXpEqn5Tjn9_hcqX3_GdIDNGobRfgDlMO;PASS_ID=1-A2WKIav5GBsz0Jp8QV6+GP5ff+Sw2kjokhgReoom02NzvMmPD/7ZQL4zxnQq4HDoUpHKB7I9J/VtNHDlNsp5YQ_186716817_29159208"
    #     },
    #     "msg": "采集评价任务"
    # }
    #
    # task = task['content']
    #
    # Helper.testCommentTask( task )

    # print( h.lenRedis() )

    # print( h.StampToDate( 1568304000 ) )

    print( Helper.redisCase('api_tasks') )


